//app.js
import { bindPhone, asynGetUserData } from './api/common';
import { baseURL } from "./utils/config";
App({
	onLaunch: function (opts) {
		/*适配iPhone X*/
		let that = this;
		wx.getSystemInfo({
			success: function (res) {
				if (/iphone\S{0,2}\s*x{1}/i.test(res.model) || /iphone\S{0,2}\s*(11){1}/i.test(res.model)) {
					that.globalData.isIphoneX = true
				}
				that.globalData.safetyArea = res.screenHeight - res.safeArea.bottom;
				that.globalData.window.w = res.windowWidth;
				that.globalData.window.h = res.windowHeight;
				that.globalData.window.scale = res.windowWidth / 375;
				that.globalData.window.all = res;
				that.globalData.window.statusHeight = res.statusBarHeight;
				that.globalData.window.navheight = res.system.indexOf('iOS') > -1 ? 44 : 48;
				that.globalData.window.isios = /ios/ig.test(res.system);

			}
		})
		// this.login()
		// !wx.getStorageSync('wxToken') && wx.redirectTo({ url: `/pages/authorization/authorization` })
	},
	globalData: {
		userInfo: null,
		isIphoneX: false,
		safetyArea: 0,
		window: {
			h: 0,
			w: 0,
			scale: 1,
			statusHeight: 0,
			navheight: 0
		},
		token: '',
		userData: {}
	},
	authorization() {
		return new Promise((resolve, reject) => {
			wx.showLoading({
				title: '授权中',
			})
			wx.getUserProfile({
				desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				lang: 'zh_CN',
				success: (res) => {
					let data = {
						encryptedData: res.encryptedData,
						iv: res.iv
					}
					bindPhone(data).then(() => {
						asynGetUserData().then(() => {
							wx.hideLoading()
							resolve()
						})
					}).catch(() =>{
						wx.showToast({
							title: '授权失败',
							icon: 'error',
							duration: 2000
						})
						wx.hideLoading()
						reject()
					})
				},
				fail() {
					wx.showToast({
						title: '授权失败, 请重新授权',
						icon: 'none',
						duration: 2000
					})
					wx.hideLoading()
				}
			})
		})
	},
	login() {
        wx.login({
            success(res) {
                if (res.code) {
                    wx.request({
                        url: `${baseURL}/api/v2/admin/sponsorAccount/sessionKey`,
                        data: { code: res.code },
                        method: 'get',
                        success: (res) => {
                            wx.setStorageSync('wxUserData', res.data.result)
                        }
                    })
                } else {
					console.log('获取code失败')
                }
            },
            fail(err) {
				console.log(err)
            }
        });
	}
})
